#include <iostream>
#include <vector>
#include "Thread.hpp"
#include "ringqueue.hpp"
#include <string>
#include"Task.hpp"
using std::cout;
using std::endl;
using namespace ThreadModule;

using ringqueue_t = RingQueue<Task>;

void Consumer(ringqueue_t *&rq,std::string name)
{
    while (true)
    {
        sleep(2);
        int data;
        //rq->Pop(&data);
        Task t;
        rq->Pop(&t);
        cout << "consumer .... " <<"------"<<"["<< name <<"]"<< endl;
        t();
    }
}

void Productor(ringqueue_t *&rq,std::string name)
{
    int cnt = 10;
    while (true)
    {
        usleep(1000);
        //rq->Enqueue(cnt);
        rq->Enqueue(Download);
        cout << "product .... "  << "------"<<"["<< name <<"]" <<endl;
        cnt++;
    }
}

void StartCom(std::vector<Thread<ringqueue_t *>> *&threads, int num, ringqueue_t *&bq, func_t<ringqueue_t *> func,std::string who)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = "thread -" + std::to_string(1 + i)+who;
        threads->emplace_back(func, bq, name);
        //threads->front().Start();
    }
}

void StartConsumer(std::vector<Thread<ringqueue_t *>> *&threads, int num, ringqueue_t *&bq)
{
    StartCom(threads, num, bq, Consumer,"consumer");
}

void StartProductor(std::vector<Thread<ringqueue_t *>> *&threads, int num, ringqueue_t *&bq)
{
    StartCom(threads, num, bq, Productor,"productor");
}

void WaitAllThread(std::vector<Thread<ringqueue_t *>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}
void StartAllThread(std::vector<Thread<ringqueue_t *>>& threads)
{
    for(auto& thread: threads)
    {
        thread.Start();
    }
}
int main()
{
    ringqueue_t *rq = new ringqueue_t(10); // 全局定义一个配合ThreadData

    std::vector<Thread<ringqueue_t *>> threads;
    std::vector<Thread<ringqueue_t *>> *pthreads = &threads;
    StartConsumer(pthreads, 3, rq);
    StartProductor(pthreads, 2, rq);
    StartAllThread(threads);
    WaitAllThread(threads);

    return 0;
}